package ar.com.nexttome;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.nexttome.context.ApplicationContext;
import ar.com.nexttome.entities.Persona;
import ar.com.nexttome.util.Constantes;
import ar.com.nexttome.util.Tools;

public class PerfilActivity extends Activity {
	
	private static int SELECT_IMAGE = 237487;
	private static int TAKE_PICTURE = 829038;
	private String mPhoneNumber = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.perfil);

		Tools.createActionMenu(this, Constantes.STR_PREFERENCIAS, MensajesActivity.class, R.drawable.ic_title_home_default);

		final RadioButton opcionM = (RadioButton)findViewById(R.id.radioM);
		opcionM.setChecked(true);

		ApplicationContext appctx = (ApplicationContext) this.getApplicationContext();
		Persona personaApp = appctx.getCurrentUser();

		TelephonyManager tMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
		mPhoneNumber = tMgr.getLine1Number();

		if(mPhoneNumber == null || mPhoneNumber.length() == 0) {
			TextView txtViewTelefono = (TextView) findViewById(R.id.titleTelefono);
			EditText editTxtTelefono =  (EditText) findViewById(R.id.telefono);
			txtViewTelefono.setVisibility(View.VISIBLE);
			editTxtTelefono.setVisibility(View.VISIBLE);
		} else {
			mPhoneNumber = mPhoneNumber.replace("+", "");
		}

		/*
		Cursor cursor = getContentResolver().query(Uri.parse("content://sms/sent"), null, null, null, null);
		cursor.moveToFirst();

		do{
		   String msgData = "";
		   for(int idx=0;idx<cursor.getColumnCount();idx++)
		   {
		       msgData += " " + cursor.getColumnName(idx) + ":" + cursor.getString(idx);
		       Toast.makeText(this, msgData, Toast.LENGTH_LONG).show();
		       break;
		   }
		}while(cursor.moveToNext());
*/

		if(personaApp == null) {
			if(mPhoneNumber != null) {
				personaApp = PersonaManager.getPerfil(mPhoneNumber);
			}
		}

		popularPerfilPersona(personaApp);
	}

	/**
	 * Si no existe la persona, muestra una imagen por default. De lo contrario, muestra la pantalla con los datos
	 *
	 */
	private void popularPerfilPersona(Persona personaApp) {

		ImageView image = (ImageView) findViewById(R.id.imagen);

		if(personaApp != null) {
			EditText etNick = (EditText) findViewById(R.id.nick);
			EditText etComentario = (EditText) findViewById(R.id.comentario);
			EditText etTel = (EditText) findViewById(R.id.telefono);

			etNick.setText(personaApp.getNick());
			etComentario.setText(personaApp.getComentario());
			etTel.setText(personaApp.getId());

			RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroupSexo);
				
			if(personaApp.getSexo().equals("M")){
				radioGroup.check(R.id.radioM);
			} else {
				radioGroup.check(R.id.radioF);
			}

			if(personaApp.getFoto()!=null) {
				image.setImageBitmap(Tools.base64ToBitmap(personaApp.getFoto()));
			} else {
				image.setImageBitmap(Tools.fileToBitmap(this,Constantes.ASSETS_DIR + Constantes.STR_FOTO_VACIA));
			}

		} else {
			image.setImageBitmap(Tools.fileToBitmap(this,Constantes.ASSETS_DIR + Constantes.STR_FOTO_VACIA));
		}
	} 

	/**
	 * Método que se ejecuta cuando obtiene la foto, ya sea por la cámara o por file system
	 *
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		ImageView image = (ImageView) findViewById(R.id.imagen);

		try {
			if (requestCode == SELECT_IMAGE) {
				if (resultCode == Activity.RESULT_OK) {
					Uri selectedImage = data.getData();
					image.setImageURI(selectedImage);
				}
			}

			if (requestCode == TAKE_PICTURE) {
				if (resultCode == Activity.RESULT_OK) {
					Bitmap imagen = (Bitmap) data.getExtras().get("data");
					image.setImageBitmap(imagen);
					image.invalidate();
				}
			}

		} catch (Exception e) {}
	}
	
	/**
	 * Modificación de imagen. Permite seleccionar del file system o de la cámara
	 *
	 */
	public void cambiarImagen(View view) {
		try {
			final CharSequence[] items = { "Seleccionar de la galería", "Tomar una foto" };

			AlertDialog.Builder builder = new AlertDialog.Builder(this);

			builder.setTitle("Seleccionar una foto");
			builder.setItems(items, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int item) {
					switch (item) {
					case 0:
						Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
						intent.setType("image/*");
						startActivityForResult(intent, SELECT_IMAGE);
						break;
					case 1:
						startActivityForResult(new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE), TAKE_PICTURE);
						break;
					}
				}
			});

			AlertDialog alert = builder.create();
			alert.show();

		} catch (Exception e) {

		}
	}

	/**
	 * Guarda el perfil. Actualiza si existe 
	 *
	 */
	public boolean guardar(View view) {
		EditText etNick = (EditText) findViewById(R.id.nick);
		EditText etTel = (EditText) findViewById(R.id.telefono);
		EditText etComentario = (EditText) findViewById(R.id.comentario);

		if (!etNick.getText().toString().equals("")) {
			if (!etTel.getText().toString().equals("") || etTel.getVisibility() == View.GONE) {
				ProgressDialog dialog = ProgressDialog.show(this, "", "Guardando perfil...", true);
				dialog.show();
			
				if(mPhoneNumber == null || mPhoneNumber.length() == 0) {
					mPhoneNumber = etTel.getText().toString();
				}

				ImageView image = (ImageView) findViewById(R.id.imagen);
				Bitmap imagen = ((BitmapDrawable)image.getDrawable()).getBitmap();
				imagen = Bitmap.createScaledBitmap(imagen, 100, 100, false);

				Persona yo = new Persona();
				yo.setId(mPhoneNumber);
				yo.setNick(etNick.getText().toString());
				yo.setComentario(etComentario.getText().toString());
				yo.setFoto(Tools.bitmapToBase64(imagen));

				RadioButton radioButtonM = (RadioButton) findViewById(R.id.radioM);

				if (radioButtonM.isChecked() ) {
					yo.setSexo("M");
				} else {
					yo.setSexo("F");
				}

				try {
					PersonaManager.guardarPerfil(yo);
					Tools.guardarPreferencias(this.getApplicationContext(), yo);
				} catch (Exception e) {
					Tools.alertReintentar(this.getApplicationContext(), Constantes.STR_GUARDAR_ERROR);
					e.printStackTrace();
				}

				Intent intent = new Intent(this, MainActivity.class);
				this.startActivity(intent);
				finish();

				return true;
			} else {
				Toast.makeText(this, Constantes.STR_PONER_TEL, Toast.LENGTH_LONG).show();
				return false;
			}
		} else {
			Toast.makeText(this, Constantes.STR_PONER_NICK, Toast.LENGTH_LONG).show();
			return false;
		}
	}
}
